package com.gl.basis.zuul.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gl.basis.auth.constants.AuthorityConstants;
import com.gl.basis.common.constant.ResultCode;
import com.gl.basis.common.pojo.CommBean;
import com.gl.basis.common.pojo.CommonResult;
import com.gl.basis.zuul.entity.SysAppManage;
import com.gl.basis.zuul.enums.RouteType;
import com.gl.basis.zuul.service.ISysAppManageService;
import com.gl.basis.zuul.util.RequestUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 调用次数
 * 
 * @author admin
 *
 */

@Component
public class UseFreuencyFilter extends ZuulFilter {
	private static final Logger logger = LoggerFactory.getLogger(UseFreuencyFilter.class);

	@Resource
	private ISysAppManageService sysAppManageService;
	@Override
	public boolean shouldFilter() {
		RequestContext currentContext = RequestContext.getCurrentContext();
		HttpServletRequest request = currentContext.getRequest();
        String path = request.getServletPath();
        //包含api就不转发
        if (!currentContext.sendZuulResponse() ||( StringUtils.isNotBlank(path)&& path.contains(RouteType.API.getCode()))) {
			return false;
		}
		return true;
	}

	@Override
	public Object run() throws ZuulException {
		RequestContext currentContext = RequestContext.getCurrentContext();
		HttpServletRequest request = currentContext.getRequest();
		String requestParams = RequestUtils.getRequestParams(currentContext, request);
		logger.info(">>>>>>请求参数："+requestParams);
		CommBean bean = JSONObject.parseObject(requestParams, CommBean.class);
		SysAppManage manage = sysAppManageService.findSerct(bean.getAppkey());
		if (manage != null && manage.getDailyVisits() <= 0 ) {
			currentContext.setSendZuulResponse(false);
			HttpServletResponse response = currentContext.getResponse();
			response.setContentType(AuthorityConstants.APPLICATION_JSON);
			currentContext.setResponseBody(JSON.toJSONString(CommonResult.failed(ResultCode.FREUECY_ERROR)));
		}else if(manage != null && StringUtils.isNotBlank(bean.getAppkey()) ) {
			//减去次数
			sysAppManageService.subtractionFreuency(bean.getAppkey());
		}
		
		
		return null;
	}

	@Override
	public String filterType() {
		return FilterConstants.POST_TYPE;
	}

	@Override
	public int filterOrder() {

		return 110;
	}

}
